package com.yinxing.webapi.config;

import com.yinxing.framework.datasource.DynamicDataSource;
import com.yinxing.framework.enums.SourceType;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 多数据源配置,配合@DataSource可在方法上使用多数据源
 * spring:
 *   datasource:
 *       master:
 *         driver-class-name: com.mysql.jdbc.Driver
 *         username: perfect
 *         password: Perfect123
 *         jdbcUrl: jdbc:mysql://39.107.219.145:3306/cabinet_box?verifyServerCertificate=false&useUnicode=true&useSSL=false
 *       slave:
 *         driver-class-name: com.mysql.jdbc.Driver
 *         username: perfect
 *         password: Perfect123
 *         jdbcUrl: jdbc:mysql://39.111.219.145:3306/cabinet_box?verifyServerCertificate=false&useUnicode=true&useSSL=false
 */
@Configuration
@ConditionalOnProperty(name = "spring.datasource.master.jdbcUrl")
public class DataSourceConfig {

    /**
     * 多数据源配置
     */
    @Bean("master")
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 多数据源配置
     */
    @Bean("slave")
    @ConfigurationProperties(prefix = "spring.datasource.slave")
    public DataSource slaveDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "dynamicDataSource")
    public DynamicDataSource dataSource(@Qualifier("master") DataSource primaryDataSource,
                                        @Qualifier("slave") DataSource slaveDataSource) {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();

        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(SourceType.master.name(), primaryDataSource);
        targetDataSources.put(SourceType.slave.name(), slaveDataSource);
        dynamicDataSource.setTargetDataSources(targetDataSources);
        dynamicDataSource.setDefaultTargetDataSource(primaryDataSource);

        return dynamicDataSource;
    }
}
